package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.TextView;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.LeTestResult;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.Recentlty_scores;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.HexagonProgress;
import com.jdy.haoduoai.view.HistogramView;
import com.jdy.haoduoai.widget.CustomCommonDialog;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

//import com.jdy.haoduoai.R;

/**
 * 
 * 
 * @author hf
 * 
 */
@SuppressLint({ "ShowToast", "InflateParams" })
public class HistoryTestResultActivity extends BaseActivity implements
    OnClickListener {
  @InjectView(id = R.id.img_gohome, click = true)
  private ImageView img_gohome;
  @InjectView(id = R.id.test_explain_btn)
  private TextView test_explain_btn;
  @InjectView(id = R.id.img_customclass, click = true)
  private ImageView img_customclass;
  @InjectView(id = R.id.img_back, click = true)
  private View img_back;
  @InjectView(id = R.id.h_scrollview, click = true)
  private HorizontalScrollView h_scrollview;
  @InjectView(id = R.id.img_device, click = true)
  private ImageView img_device;
  @InjectView(id = R.id.tv_testconclusion)
  private TextView tv_testconclusion;
  @InjectView(id = R.id.hexagonProgress2)
  private HexagonProgress hexagonProgress2;
  @InjectView(id = R.id.tv_jump2main)
  private TextView tv_jump2main;
  @InjectView(id = R.id.img_recustom, click = true)
  private ImageView img_recustom;

  @InjectView(id = R.id.view_jump2main, click = true)
  private View view_jump2main;
  @InjectView(id = R.id.tv_score, click = true)
  private TextView tv_score;

  private HistogramView mHistogramView;

  private final static int REQUEST_ABILITY_TEST = 100;

  @SuppressWarnings("unused")
  private int total_score, score;

  // 测评详情
  private LeTestResult mTestResultDetail;
  private float cognition; // 认知能力
  private float fine_motion; // 精细活动
  private float social; // 社交
  private float self_caring; // 自理
  private float muscle; // 大肌肉运动
  private float language; // 语言

  private boolean isregisterflow, frommainpage, getScore;
  private int totalMonth;
  private Drawable mDrawable;
  int TEST_MODE;

  private void updateBtnState() {

    switch (TEST_MODE) {
    case 1: // 无入口
      img_customclass.setVisibility(View.GONE);
      // test_explain_btn.setVisibility(View.VISIBLE);
      img_recustom.setVisibility(View.VISIBLE);
      view_jump2main.setVisibility(View.GONE);
      break;
    case 2: // 测试入口
      img_customclass.setVisibility(View.VISIBLE);
      test_explain_btn.setVisibility(View.GONE);
      img_recustom.setVisibility(View.GONE);
      view_jump2main.setVisibility(View.GONE);
      break;

    default:
      view_jump2main.setVisibility(View.VISIBLE);
      break;
    }

    if (Tools.isEmpty(mTestResultDetail.info)) {
      return;
    } else {
      if (!mTestResultDetail.info.can_test
          && Tools.isNotEmpty(mTestResultDetail.info.next_test_date)) {
        img_customclass.setVisibility(View.GONE);
        // test_explain_btn.setVisibility(View.VISIBLE);
        img_recustom.setVisibility(View.VISIBLE);
      } else {
        img_customclass.setVisibility(View.VISIBLE);
        test_explain_btn.setVisibility(View.GONE);
        img_recustom.setVisibility(View.GONE);
      }
    }
  }

  private void checkBabyAge() {
    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
    if (lu != null) {
      if (Tools.isNotEmpty(lu.machine)) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
          Calendar bef = Calendar.getInstance();
          bef.setTime(sdf.parse(lu.machine.dob));

          int month = Calendar.getInstance().get(Calendar.MONTH)
              - bef.get(Calendar.MONTH);

          int year = Calendar.getInstance().get(Calendar.YEAR)
              - bef.get(Calendar.YEAR);

          int totalMonth = year * 12 + month;
          if (totalMonth == 0) {
            totalMonth = 1;
          }

          if (totalMonth < 12) {
            setTitle(totalMonth + "月龄成长概况");
          } else {
            int year1 = totalMonth / 12;
            int month1 = totalMonth % 12;

            if (month1 > 0) {
              setTitle(year1 + "岁" + month1 + "月龄成长概况");
            } else {
              setTitle(year1 + "岁" + "龄成长概况");
            }
          }
        } catch (Exception e) {
          // TODO: handle exception
        }
      }
    }
  }

  private void checkBabyAge2() {
    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
    if (lu != null && Tools.isNotEmpty(lu.machine)) {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

      try {
        Calendar bef = Calendar.getInstance();
        bef.setTime(sdf.parse(lu.machine.dob));

        int month = Calendar.getInstance().get(Calendar.MONTH)
            - bef.get(Calendar.MONTH);

        int year = Calendar.getInstance().get(Calendar.YEAR)
            - bef.get(Calendar.YEAR);

        totalMonth = year * 12 + month;
        if (totalMonth == 0) {
          totalMonth = 1;
        }

      } catch (Exception e) {
        // TODO: handle exception
      }
    }
  }

  @Override
  @SuppressLint("InflateParams")
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_testresult);

    Intent it = getIntent();
    if (it != null) {
      // mTestResultDetail = (LeTestResult) it
      // .getSerializableExtra("mTestResultDetail");
      isregisterflow = it.getBooleanExtra("registerflow", false);
      getScore = it.getBooleanExtra("getScore", false);
      frommainpage = it.getBooleanExtra("frommainpage", false);

      TEST_MODE = it.getIntExtra("TEST_MODE", -1);
    }

    checkBabyAge2();

    img_recustom.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    mDrawable = getResources().getDrawable(R.drawable.nextstep_icon);

    tv_jump2main.setText("立即查看宝宝成长计划");
    tv_jump2main
        .setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
    // if (totalMonth < (12 * 6) && totalMonth > 12) {
    // tv_jump2main.setText("我的宝宝我知道");
    // tv_jump2main.setCompoundDrawablesWithIntrinsicBounds(mDrawable, null,
    // null, null);
    // } else {
    // tv_jump2main.setText("立即查看课程");
    // tv_jump2main.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
    // null);
    // }

    if (frommainpage) {
      view_jump2main.setVisibility(View.GONE);
    }

    getDetail();

    mBackImageButton.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        recustomClassTip();
      }
    });
  }

  private void recustomClassTip() {
    if (view_jump2main.getVisibility() == View.VISIBLE) {
      CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
          HistoryTestResultActivity.this).setMessage("是否重新定制课程？")
          .setNegativeButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();

              Intent it = new Intent(HistoryTestResultActivity.this,
                  AbilityTestExplainActivity.class);
              it.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
              startActivity(it);

              finish();
            }
          }).setPositiveButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

              dialog.dismiss();
            }
          });
      if (!isFinishing()) {
        cdb.create().show();
      }
    } else {
      finish();
    }
  }

  private void updateSixShape() {

    if (Tools.isNotEmpty(mTestResultDetail)
        && Tools.isNotEmpty(mTestResultDetail.recently_test_result)
        && Tools.isNotEmpty(mTestResultDetail.recently_test_result.catalog)) {
      cognition = (mTestResultDetail.recently_test_result.catalog.cognition.rating + 0.0f)
          / mTestResultDetail.recently_test_result.catalog.cognition.full_rating;

      fine_motion = (mTestResultDetail.recently_test_result.catalog.fine_motion.rating + 0.0f)
          / mTestResultDetail.recently_test_result.catalog.fine_motion.full_rating;

      social = (mTestResultDetail.recently_test_result.catalog.social.rating + 0.0f)
          / mTestResultDetail.recently_test_result.catalog.social.full_rating;

      self_caring = (mTestResultDetail.recently_test_result.catalog.self_caring.rating + 0.0f)
          / mTestResultDetail.recently_test_result.catalog.self_caring.full_rating;

      muscle = (mTestResultDetail.recently_test_result.catalog.muscle.rating + 0.0f)
          / mTestResultDetail.recently_test_result.catalog.muscle.full_rating;

      language = (mTestResultDetail.recently_test_result.catalog.language.rating + 0.0f)
          / mTestResultDetail.recently_test_result.catalog.language.full_rating;

      hexagonProgress2.updateScore(cognition, fine_motion, social, self_caring,
          muscle, language);
    }

    dismissLoading();
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode,
      Intent returnedIntent) {
    super.onActivityResult(requestCode, resultCode, returnedIntent);
    switch (requestCode) {
    case REQUEST_ABILITY_TEST:
      if (resultCode == RESULT_OK) {
        // mTestResultDetail = (LeTestResult) returnedIntent
        // .getSerializableExtra("mTestResultDetail");
        getScore = returnedIntent.getBooleanExtra("getScore", false);

        checkBabyAge2();

        img_recustom.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
        mDrawable = getResources().getDrawable(R.drawable.nextstep_icon);

        tv_jump2main.setText("立即查看宝宝成长计划");
        tv_jump2main.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
            null);

        getDetail();

        mBackImageButton.setOnClickListener(new OnClickListener() {
          @Override
          public void onClick(View v) {
            recustomClassTip();
          }
        });

        view_jump2main.setVisibility(View.VISIBLE);
      }
      break;

    }
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.img_recustom:
    case R.id.img_customclass:
      Intent ttt;
      ttt = new Intent(this, AbilityTestActivity.class);
      ttt.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      ttt.putExtra("startActivityForResult", true);
      startActivityForResult(ttt, REQUEST_ABILITY_TEST);
      // startActivity(ttt);
      overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
      // finish();

      break;
    case R.id.view_jump2main:
      Intent intent0;

      intent0 = new Intent(this, MainActivity.class);

      // if (tv_jump2main.getText().toString().contains("我的宝宝我知道")) {
      // intent0 = new Intent(this, AttractNewRepelActivity.class);
      // } else {
      //
      // }

      // LeConfig.bRefreshMainPage = true;

      intent0.putExtra("getScore", getScore);
      intent0.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      startActivity(intent0);
      overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
      // finish();

      break;
    case R.id.img_gohome:
      Intent intent = new Intent(this, MainActivity.class);
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      startActivity(intent);
      break;
    case R.id.test_explain_btn:
      Intent intent1 = new Intent(this, TestSpecificationActivity.class);
      intent1.putExtra("title", "测试说明");
      intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
      startActivity(intent1);
      break;
    case R.id.img_back:
      if (view_jump2main.getVisibility() == View.VISIBLE) {
        CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(this)
            .setMessage("是否重新定制课程？")
            .setNegativeButton("是", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                Intent it = new Intent(HistoryTestResultActivity.this,
                    AbilityTestExplainActivity.class);
                it.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(it);

                finish();
              }
            }).setPositiveButton("否", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();
              }
            });
        if (!isFinishing()) {
          cdb.create().show();
        }
      }

      break;
    case R.id.img_device:
      if (LeConfig.isLogin) {
        startActivity(new Intent(this, DevicePropertyActivity.class));
      } else {
        Intent intent2 = new Intent(this, LoginActivity.class);
        intent2.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent2);
      }
      break;
    default:
      break;
    }
  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
      if (view_jump2main.getVisibility() == View.VISIBLE) {
        recustomClassTip();
        return true;
      } else {
        return super.onKeyDown(keyCode, event);
      }

    }
    return super.onKeyDown(keyCode, event);
  }

  private void fillViews() {
    updateSixShape();

    if (Tools.isNotEmpty(mTestResultDetail.recently_test_result)) {
      tv_testconclusion.setText(mTestResultDetail.recently_test_result.summary);
      tv_score.setText(mTestResultDetail.recently_test_result.score + "");
    }

    if (Tools.isNotEmpty(mTestResultDetail.info)) {
      test_explain_btn.setText("下次测评:" + mTestResultDetail.info.next_test_date);
      setTitle(mTestResultDetail.info.title + "成长概况");
    } else {
      checkBabyAge();
    }

    updateBtnState();

    if (mHistogramView == null) {
      mHistogramView = new HistogramView(HistoryTestResultActivity.this);
    }

    mHistogramView
        .initValues((ArrayList<Recentlty_scores>) mTestResultDetail.recently_scores);
    h_scrollview.removeAllViews();
    h_scrollview.addView(mHistogramView);

    int size = mTestResultDetail.recently_scores.size();
    if (size >= 1) {
      tv_score
          .setText(mTestResultDetail.recently_scores.get(size - 1).test_score
              + mTestResultDetail.recently_scores.get(size - 1).action_score
              + "");
    }

    handler.postDelayed((new Runnable() {
      @Override
      public void run() {
        h_scrollview.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
      }
    }), 100);

  }

  private void getDetail() {
    showloading("");
    if (mHistogramView == null) {
      mHistogramView = new HistogramView(this);
    }

    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, final ResponseResult result) {
        if (result.isSuccess()) {
          mTestResultDetail = JsonSerializer.getInstance().deserialize(
              result.data, LeTestResult.class);
          if (Tools.isNotEmpty(mTestResultDetail)) {
            fillViews();
          }
        } else {
          toastShow(result.data);
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/operation/growth_test", param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }
}
